package com.flute.icrawler.app.processor.fetch;

import java.net.InetAddress;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.UnknownHostException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.flute.icrawler.app.processor.AbstractProcessor;
import com.flute.icrawler.app.service.CrawlService;
import com.flute.icrawler.framework.framework.CrawlUrl;
import com.flute.icrawler.framework.processor.result.FailProcessorResult;
import com.flute.icrawler.framework.processor.result.SuccessProcessorResult;

public class FetchDNS extends AbstractProcessor {
	private static final Logger LOGGER = LoggerFactory
			.getLogger(FetchDNS.class);

	public void process(CrawlUrl crawlUrl) {

		LOGGER.info("FetchDNS:{}", crawlUrl.getUrl());

		URI uri = null;
		try {
			uri = new URI(crawlUrl.getUrl());
		} catch (URISyntaxException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			crawlUrl.registerProcessorResult(new FailProcessorResult());
			return;
		}

		String dnsName = uri.getHost();

		// 查找其DNS地址 看是否有
		boolean hasDNS = CrawlService.getInstance().registerDNS(dnsName);

		// 如果没有DNS 则该链接肯定无法连上
		if (!hasDNS) {
			crawlUrl.registerProcessorResult(new FailProcessorResult());
			return;
		}

		// 是否需要使用javaDNS进行检查
		boolean needJavaDNSCheck = false;

		if (needJavaDNSCheck) {
			// Do lookup that bypasses javadns.
			InetAddress address = null;
			try {
				address = InetAddress.getByName(dnsName);
			} catch (UnknownHostException e1) {
				address = null;
			}
			if (address != null) {
				// TODO 检查通过
				crawlUrl.registerProcessorResult(new SuccessProcessorResult());
			}
		}

	}

	public static void main(String[] args) {

		CrawlUrl crawlUrl = new CrawlUrl(null, "http://music.douban.com");
		new FetchDNS().process(crawlUrl);

	}
}
